import 'dart:io';

import 'package:cave_flutter/network/whl_api.dart';
import 'package:cave_flutter/network/whl_http_manager.dart';
import 'package:cave_flutter/utils/whl_permission_util.dart';
import 'package:cave_flutter/utils/whl_toast_utils.dart';
import 'package:cave_flutter/widgets/whl_image_editor_view.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:get/get.dart' hide MultipartFile;
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:http_parser/http_parser.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';
import '../style/whl_style.dart';

class AvatarUtils {
  static onCameraPicker(BuildContext context, {Function(String filePath)? onSuccess}) async {
    WhlPermissionUtil.reqCameraPermission(onSuccessAction: () async {
      AssetEntity? assetEntity = await CameraPicker.pickFromCamera(context, locale: const Locale('en', 'US'));
      if (assetEntity == null) return;
      onCompressPhoto(assetEntity, onSuccess: onSuccess);
    });
  }

  static onChoosePhoto(BuildContext context, {Function(String filePath)? onSelectEnd,Function(String url)? onSuccess}) async {
    WhlPermissionUtil.reqStoragePermission(onSuccessAction: () async {
      final List<AssetEntity> assets =
          await AssetPicker.pickAssets(context, pickerConfig: AssetPickerConfig(themeColor: kAppThemeColor, requestType: RequestType.image, maxAssets: 1), useRootNavigator: false) ?? [];
      if (assets.isEmpty) return;
      onCompressPhoto(assets.first, onSelectEnd: onSelectEnd ,onSuccess: onSuccess);
    });
  }

  static onCompressPhoto(AssetEntity assetEntity, {Function(String filePath)? onSelectEnd,Function(String filePath)? onSuccess}) async {
    File? pickedFile = await assetEntity.file;
    print('压缩前图片文件大小:${pickedFile?.lengthSync()}');
    if (pickedFile != null) {
      int fileSize = await pickedFile.length();
      //裁剪图片
      String? resultPath = await Get.to(() => WhlImageEditorView(filePath: pickedFile!.path));
      if (resultPath != null) {
        pickedFile = File(resultPath);
        fileSize = await pickedFile.length();
        print('压缩前fileSize:$fileSize');
        int compressCount = 0;
        // 图片大于200kb，压缩
        XFile? compressFile = XFile(pickedFile.path);
        while (fileSize > 200 * 1024) {
          compressCount++;
          if (compressCount == 4) {
            // 压缩次数超过3次，不再压缩
            break;
          }
          compressFile = await FlutterImageCompress.compressAndGetFile(
            compressFile?.path ?? '',
            '${Directory.systemTemp.path}/userAvatar${DateTime.now().millisecondsSinceEpoch}.jpg',
            quality: 30,
          );
          if (compressFile != null) {
            fileSize = await compressFile!.length();
            print('压缩后fileSize:$fileSize');
          } else {
            fileSize = 0;
            // onError.call('');
          }
        }
        if (fileSize > 0 && compressFile != null) {
          if (onSelectEnd != null) {
            onSelectEnd(compressFile.path);
          }
          onGetOssPolicy(compressFile.path, onSuccess: onSuccess);
        }
      }
    } else {
      // onError.call('');
    }
  }

  static onGetOssPolicy(String filePath, {Function(String filePath)? onSuccess}) async {
    // BotToast.showLoading();
    String chuo = DateTime.now().millisecondsSinceEpoch.toString() + filePath.substring(filePath.lastIndexOf('.'));
    var mapEntry = await MultipartFile.fromFile(filePath, filename: chuo, contentType: MediaType.parse("image/png"));
    Map<String, dynamic> params = {'path': 'avatar', 'file': mapEntry};
    ResponseData responseData = await WhlApi.uploadFile.post(params,isJson: false);
    if (responseData.isSuccess()) {
      // BotToast.closeAllLoading();
      String url = responseData.data["url"]??"";
      onSuccess?.call(url);
    }else {
      onSuccess?.call("");
      MyToast.show("头像上传失败");
    }
  }
}

class WhlOssModel {
  String? accessKeyId;
  String? policy;
  String? signature;
  String? expire;
  String? dir;
  String? host;
  String? callback;

  WhlOssModel({this.accessKeyId, this.policy, this.signature, this.expire, this.dir, this.host, this.callback});

  WhlOssModel.fromJson(Map<String, dynamic> json) {
    accessKeyId = json['accessKeyId'];
    policy = json['policy'];
    signature = json['signature'];
    expire = json['expire'];
    dir = json['dir'];
    host = json['host'];
    callback = json['callback'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['accessKeyId'] = this.accessKeyId;
    data['policy'] = this.policy;
    data['signature'] = this.signature;
    data['expire'] = this.expire;
    data['dir'] = this.dir;
    data['host'] = this.host;
    data['callback'] = this.callback;
    return data;
  }
}
